<?php
@ob_start();
@session_start();
include("checkSession.php");
error_reporting (E_ALL ^ E_NOTICE);
require_once("../../includes/GPSFunction.php");
//require_once("User.php");

//	DB Connection
require_once("../../includes/config.inc.php"); 
require_once("../../includes/Database.class.php"); 
require_once("../../includes/pagination.php");
$db = new Database(DB_SERVER, DB_USER, DB_PASS, DB_DATABASE); 
$db->connect(); 
include("Util.php"); 
$util =  new Util();
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>GPS Application</title>
<link href="../../css/style.css" rel="stylesheet" type="text/css" />

<style type="text/css">
#results div
{	position: absolute;
	visibility: hidden;
	margin: 0;
	padding: 0;
	left:78%;
	background: #FBAD2A;
	border: 0px solid #5970B2
}

#results div a
{	position: relative;
	display: block;
	margin: 0;
	padding: 5px 10px;
	width: auto;
	white-space: nowrap;
	text-align: left;
	text-decoration: none;
	background: #FBAD2A;
	color: #fff;
	font: 12px bold Arial, Helvetica, sans-serif
}

#results div a:hover
{	background: #49A3FF;
	color: #FFF
}
</style>
<script src="../../js/ajax.js" type="text/javascript"></script>
<script src="http://maps.google.com/maps?file=api&amp;v=2.x&amp;key=<?php echo GOOGLE_API_KEY;?>" type="text/javascript"></script>
<script type="text/javascript" src="../../js/pagination.js"></script>

<script language="javascript">
var ajax1=new sack();
function findLocat(point,divId)
{
	document.getElementById(divId).innerHTML = "Loading...";
	var latlngStr = point.split("-",2);
    var lat = parseFloat(latlngStr[0]);
    var lng = parseFloat(latlngStr[1]);
	var address =lat+","+lng
	/*var geocoder2 = new GClientGeocoder();
	geocoder2.getLocations(address, function(response) {
	  if (!response || response.Status.code != 200) {
		//alert("Status Code:" + response.Status.code);
		document.getElementById(divId).innerHTML= "Status Code: not identified";
	  } else {
	  	//alert(address+" "+response.name)
		place = response.Placemark[0];
	
		addr=place.address;*/
		ajax1.requestFile = 'ajax_server.php?FetchUDLoca=1&lat='+lat+'&lng='+lng;		//+'&addr='+addr;				
		//alert(ajax1.requestFile);
		ajax1.onCompletion = function(){
		//alert(ajax1.response)
			document.getElementById(divId).innerHTML= ajax1.response;
		};
		ajax1.runAJAX();		
		
		//document.write(addr);
	//}
	//});
}

function funEditUser(did)
{
	//alert(did)
	document.frmSubmit.txtAlertId.value = did;
	document.frmSubmit.action = "index.php?ch=myalerts";
	document.frmSubmit.target= "_blank";
	document.frmSubmit.submit();
}

function openPath(vid,date,ssId,rFlag)
{
	document.frmTripData.txtVehino.value = vid;
	document.frmTripData.txtDate.value = date;
	document.frmTripData.txtSessId.value = ssId;
	document.frmTripData.txtRunFlag.value = rFlag;
	document.frmTripData.submit();
}
var imeiArr = [];
function callData(val,dateoff,index)
{
	imeiArr.push(val+","+dateoff+","+index)
	//alert(imeiArr)
}
function refreshPage()
{
	window.location.reload();
}
</script>
<script type="text/javascript">
<!--
var timeout         = 500;
var closetimer		= 0;
var ddmenuitem      = 0;

// open hidden layer
function mopen(id)
{	
	// cancel close timer
	mcancelclosetime();

	// close old layer
	if(ddmenuitem) ddmenuitem.style.visibility = 'hidden';

	// get new layer and show it
	ddmenuitem = document.getElementById(id);
	ddmenuitem.style.visibility = 'visible';

}
// close showed layer
function mclose()
{
	if(ddmenuitem) ddmenuitem.style.visibility = 'hidden';
}

// go close timer
function mclosetime()
{
	closetimer = window.setTimeout(mclose, timeout);
}

// cancel close timer
function mcancelclosetime()
{
	if(closetimer)
	{
		window.clearTimeout(closetimer);
		closetimer = null;
	}
}

// close layer when click-out
//document.onclick = mclose; 
// -->
</script>
<?php
function chk_folder($filename)
{
	$fp_load = @fopen("$filename", "rb");
	if ( $fp_load )
	{
		return true;
	}
	else
	{
		return false;
	}
}
function gpspathFun($source)
{
	$file1 = @fopen($source, "r");
	if($file1)
	{
		while(!@feof($file1))
		{
		   $data= @fgets($file1);				 
		   //$i++;
		}
		$data = getSortedData($data);
		return $data;
		
	}
	else
	{
		return 0;
	}
	@fclose($file1);
}

function ReversSordData($data1)
{
	$dataArr = explode('#',$data1);
	for($i=0;$i<count($dataArr)-1;$i++)
	{
		$dtArray = explode(',',$dataArr[$i]);
		//print_r($dtArray);
		$newDate=$dtArray[9];
		$newdtArray1[$newDate] = $dataArr[$i];
	}
	ksort($newdtArray1);
 	$data = end($newdtArray1)."#";
	return $data;
}

function kmsPerToDay($path1)
{ 
	//echo 'ss'.$path1;
	$timeArr = array();
	$cnt = 1;
	$totalDistance = 0;
	//$geocode = get_url($path1);
	
  	$file1 = @fopen($path1, "r");
	if($file1)
	{
		//echo $path1;
		while(!feof($file1))
		{
			
			$data= @fgets($file1);				 
		}
		$data = ReversSordData($data);
		$data1=explode("#",$data);
		//print_r($data1);
		for($j1=0;$j1<count($data1);$j1++)
		{
			$data2=explode("@",$data1[$j1]);
			if(count($data2)>1)
			{
				$data3=explode(",",$data2[1]);	
				$vehi=$data3[0];
				
				$geodate = $data3[8];
				$geoTime = date("h:i:s A",strtotime($data3[9]));
				
				$pos1=calLat($data3[2]);
				$pos2=calLong($data3[1]);
				if($pos1>0 && $pos2>0)
				{
					if(!in_array($geoTime,$timeArr))
					{
						if($j1==0)
						{
							$pits1 =  $pos1;
							$pits2 =  $pos2;
						}
						else
						{
							$pits3 =  $pos1;
							$pits4 =  $pos2;
							
							$dist = getDistance($pits1, $pits2, $pits3, $pits4);
							$totalDistance += $dist;
							$pits1 =  $pits3;
							$pits2 =  $pits4;
						}
				
					}
				}
			}
			array_push($timeArr,$geoTime);
		}
		$findLatLng = $pits1."-".$pits2;

 		//$locat=explode(">",getGeocode($findLatLng,"COORADDR"));
 		//$locat = str_replace(",","-",$locat[2]); 
		$finalData = round($totalDistance).",".$findLatLng.",".$data3[3].",".$geodate.",".$geoTime;

		@fclose($file1);
		return $finalData;
	}
	else
	{
		return false;
	}
}

function getDistanceFromDB($distDate,$devImei)
{
$db = new Database(DB_SERVER, DB_USER, DB_PASS, DB_DATABASE); 
$db->connect(); 

	$getDateReading = "SELECT * FROM tb_speed_meter_info WHERE tmsi_clientId = ".$_SESSION[clientID]." AND tmsi_imei = '".$devImei."' AND tmsi_readDate = '".date('Y-m-d',strtotime($distDate))."'";
	$resDateReading = $db->query($getDateReading);
	if($db->affected_rows == 0)
	{		
		return -1;
	}
	else
	{
		$fetDateReading = $db->fetch_array($resDateReading);
		
		return $fetDateReading[tmsi_kmpd];
	}
	
}
function kmsPerDay($path1)
{ 
$db = new Database(DB_SERVER, DB_USER, DB_PASS, DB_DATABASE); 
$db->connect(); 
	//echo 'ss'.$path1;
	$timeArr = array();
	$cnt = 1;
	$totalDistance = 0;
	//$geocode = get_url($path1);
	
  	$handle = @fopen($path1, "r");
	if($handle)
	{
		//echo $path1;
		$data= @fgets($handle);				 
		$data = getSortedData($data);
		$data1=explode("#",$data);
		//print_r($data1);
		//exit;
		for($j1=0;$j1<count($data1);$j1++)
		{
			$data2=explode("@",$data1[$j1]);
			if(count($data2)>1)
			{
				$data3=explode(",",$data2[1]);	
				$vehi=$data3[0];
				
				$geodate = $data3[8];
				$geoTime = date("h:i:s A",strtotime($data3[9]));
				
				$pos1=calLat($data3[2]);
				$pos2=calLong($data3[1]);
				if($pos1>0 && $pos2>0)
				{
					if(!in_array($geoTime,$timeArr))
					{
						if($j1==0)
						{
							$pits1 =  $pos1;
							$pits2 =  $pos2;
						}
						else
						{
							$pits3 =  $pos1;
							$pits4 =  $pos2;
							
							$dist = getDistance($pits1, $pits2, $pits3, $pits4);
							$totalDistance += $dist;
							$pits1 =  $pits3;
							$pits2 =  $pits4;
						}
				
					}
				}
			}
			array_push($timeArr,$geoTime);
		}
		//$findLatLng = $pits1."-".$pits2;

 		//$locat=explode(">",getGeocode($findLatLng,"COORADDR"));
 		//$locat = str_replace(",","-",$locat[2]); 
		//$finalData = round($totalDistance,2).",".implode(",",$data3);
		@fclose($file1);
		
		$livedata["tli_imei"] = $data3[0];
		$livedata["tli_parameter"] = "@".implode(",",$data3)."#";
		$livedata["tli_distance"] = round($totalDistance,4);
		$livedata["tli_date"] = $data3[8];
		$livedata["tli_time"] = $data3[9];
		$livedata["tli_updateTime"] = 'NOW()';
		//print_r($livedata);exit;
		if($db->query_insert("tb_livegps_info", $livedata))
		{
			return true;
		}
		else
		{
			return false;
		}
	}
	else
	{
		return false;
	}
}
function insertMeterData($devData)
{
	$db = new Database(DB_SERVER, DB_USER, DB_PASS, DB_DATABASE); 
	$db->connect(); 
	$devData = explode("#",$devData);
	$getLiveData = "SELECT * FROM tb_livegps_info WHERE tli_imei = '".$devData[0]."'";
	$exeLiveData = $db->query($getLiveData);
	if($db->affected_rows > 0)
	{
		$fetLiveData = $db->fetch_array($exeLiveData);
		//print_r($fetLiveData);
		$odoMeter = $fetLiveData[tli_distance];
		$lastData1=explode("#",$fetLiveData[tli_parameter]);
		$lastData2=explode("@",$lastData1[0]);
		$lvData = ($fetLiveData[tli_distance]+$devData[1]).','.$lastData2[1].','.$fetLiveData[tli_today];
		return $lvData;
	}
}
	if(isset($_GET[date_offline]) && $_GET[date_offline])
		$date_offline = $_GET[date_offline];
	else
		$date_offline = date('d-m-Y');
	
	$getUserInfo = "SELECT * FROM tb_userinfo,tb_clientinfo WHERE ui_id  = ".$_SESSION[userID]." AND ci_id = ".$_SESSION[clientID];
	$resUserInfo = $db->query($getUserInfo);

	if($db->affected_rows > 0){
	$recordUserInfo = $db->fetch_array($resUserInfo);
	}
	
	if($recordUserInfo[ci_clientType] == "Client" && $recordUserInfo[ui_isAdmin] == "1")
	{
		$getDevice = "SELECT * FROM tb_deviceinfo,tb_client_subscription,tb_clientinfo WHERE tcs_isActive = 1 AND tcs_deviceId = di_id AND di_status = 1 AND di_clientId=ci_id AND ci_id=".$_SESSION[clientID]." order by di_deviceName,di_deviceId,ci_clientName ASC";
	}
	else if($recordUserInfo[ci_clientType] == "Client" && $recordUserInfo[ui_isAdmin] == "0" && $recordUserInfo[ui_roleId] == "1")
	{
		$getDevice = "SELECT * FROM tb_deviceinfo,tb_client_subscription WHERE tcs_isActive = 1 AND tcs_deviceId = di_id AND di_status = 1 AND di_clientId=".$_SESSION[clientID]." AND di_assignedUserId = ".$_SESSION[userID]." ORDER BY di_deviceName,di_deviceId ASC";
	}
	else if($recordUserInfo[ci_clientType] == "Reseller")
	{
		$getDevice = "SELECT * FROM tb_deviceinfo,tb_clientinfo,tb_client_subscription WHERE tcs_isActive = 1 AND tcs_deviceId = di_id AND di_status = 1 AND di_clientId = ci_id AND ci_clientId=".$_SESSION[clientID]." order by di_deviceName,di_deviceId,ci_clientName ASC";
	}
	
	$resDevice= $db->query($getDevice);	
	$tot=$db->affected_rows;
	$getDevice .=" limit ".$s.",".$n;
	$resDevice= $db->query($getDevice);	
	//exit;
	$tmpId='';
	$destArr=array();
	
	if($tot > 0 )
	{
		while ($fetDevice = $db->fetch_array($resDevice)) 
		{
			//print_r($fetDevice);
			if($fetDevice[di_deviceName])
				$devName = $fetDevice[di_deviceName];
			else
				$devName = $fetDevice[di_deviceId];
			$devImage = $fetDevice[di_deviceImg];
				
			$renewDate = date("d-m-Y",strtotime("-1 days ".$fetDevice[tcs_renewalDateTo]));
			//echo $date_offline." <= ".date("d-m-Y",strtotime($renewDate))."<br>";
			if(strtotime($date_offline) <= strtotime($renewDate))
			{				
				$sdate = date("d-m-Y",strtotime($fetDevice[di_createDate]));
				$edate = date("d-m-Y");
				
				$z = GetDays($sdate, $edate);				
				
				$getDeviceId = "SELECT * FROM tb_client_driver_info WHERE tcdi_id =".$fetDevice[di_assignedDriverId];
				$resDeviceId = $db->query($getDeviceId);
				if($db->affected_rows > 0)
				{
					$fetDriver = $db->fetch_array($resDeviceId);				
					$driver = '<img src="images/driver.png" width="50" height="40" alt="'.$fetDriver[tcdi_mobile].'" title="'.$fetDriver[tcdi_mobile].'"/><br>'.ucfirst($fetDriver[tcdi_driverName]);
				}
				else
				{
					$driver = 'NA';
				}
								
				$getAlert = "select * from tb_device_alert_info where tdai_active = 1 AND tdai_status = 0 AND tdai_deviceId = ".$fetDevice[di_id]." AND tdai_clientId = ".$_SESSION[clientID];
				$resAlert = $db->query($getAlert);
				if($db->affected_rows > 0)
				{
					$alrts = '<div id="'.$fetDevice[di_id].'" onmouseover="mcancelclosetime()" onmouseout="mclosetime()">';
					while($fetAlert = $db->fetch_array($resAlert))
					{
						$alrts .= '<a href="#" title="Click to edit" onclick="funEditUser('.$fetAlert[tdai_id].')">'.$fetAlert[tdai_purpose]." - ".$fetAlert[tdai_alertBy].'</a>';					
					}
					$alrts .= '</div>';
				}
				else $alrts ="";
				
				$res = insertMeterData($fetDevice[di_imeiId]."#".$fetDevice[di_odoMeter]);
				//print_r($res);	
				if(count($res) > 0 )
				{
					$km = $res;
					$km = explode(",",$km);	
					//print_r($res);		
				}				
				else
				{
					for($y=count($z)-1; $y>=0; $y--)
					{					
						$path = DATAPATH.date('d-m-Y',strtotime($z[$y]))."/".$fetDevice[di_imeiId].".txt";
						$fp_load = chk_folder($path);
						if ($fp_load)
						{
							if(kmsPerDay($path))												
							{
								$km = insertMeterData($fetDevice[di_imeiId]."#".$fetDevice[di_odoMeter]);								
							}
							//print_r($km);							
							break;
						}	
					}
				}

				//print_r($km);
				$odoMeter = $km[0];
				$todatMeter = $km[11];
				//echo strtotime(date("H:i"))."-".strtotime(date("H:i",strtotime($km[4])))."<br>";
				if($km[10] != "")
				{
					$diffTime = ((strtotime(date("H:i"))-strtotime(date("H:i",strtotime($km[10]))))/60);

					if( $diffTime >= 0 && $diffTime <= 5)
					{
						$meterArr[] = ucfirst($fetDevice[ci_clientName]).",".$devName.",".$odoMeter.",".$renewDate.",a,".$km[4].",".calLat($km[2]).",".calLong($km[3]).",".$km[4].",".$km[9].",".$km[10].",1".",".$devImage.",".$alrts.",".$fetDevice[di_id].','.$driver.','.$todatMeter.','.$fetDevice[di_imeiId].','.$fetDevice[di_clientId];
					}
					else
					{
						$meterArr[] = ucfirst($fetDevice[ci_clientName]).",".$devName.",".$odoMeter.",".$renewDate.",a,".$km[4].",".calLat($km[2]).",".calLong($km[3]).",".$km[4].",".$km[9].",".$km[10].",2".",".$devImage.",".$alrts.",".$fetDevice[di_id].','.$driver.','.$todatMeter.','.$fetDevice[di_imeiId].','.$fetDevice[di_clientId];
				}
				}
				else
				{
					$meterArr[] = ucfirst($fetDevice[ci_clientName]).",".$devName.",".$odoMeter.",".$renewDate.",b,,,,,,,,,".$devImage;
				}
						
			}
			else
			{
				$meterArr[] = ucfirst($fetDevice[ci_clientName]).",".$devName.",".$odoMeter.",".$renewDate.",Subscription Date Expired.Please Renew the Unit,,,,,,,,".$devImage;
			}
			$km = "";
			$alrts = "";
			//echo "<br>";
		}	// While
?>
<!--<div align="left" class="listofusers">&nbsp;<a href="#" onclick="refreshPage()">Refresh</a>&nbsp;</div>
--><div id="homeMap">
	<table width="100%" class="gridform_final" id="results">
    <tr>
	   	<th width="5%" align="left">#</th><th width="8%" align="left">Device</th><th width="8%" align="left">Driver</th><th align="left">Location</th><th width="13%" align="left">Last Recv.</th><th width="10%" align="left">OdoMeter</th><th width="7%" align="left">Subscription <br />Exp. Date</th><th width="5%" align="left">Alerts</th><th width="5%" align="left">Status</th><th width="5%" align="left">Map</th>
     
     </tr>
     <?php 
	 	//print_r($meterArr); 
		if(count($meterArr)>0)
		{
			$c = 1;
			for ($i = 0; $i < count($meterArr); $i++)
			{
				$data = explode(',',$meterArr[$i]);
				//print_r($data);
				//echo $data[10];
				if($data[5]==0)
					$status = '<img src="images/stop.gif" width="25px" height="25px" title="Stopped"/>';
				if($data[5]>0)
					$status = '<img src="images/run.gif" width="25px" height="25px" title="Running"/>';
				else if($data[5] == "")
					$status = '<img src="images/idle.gif" width="25px" height="25px" title="No $data for today"/>';
				
				if($data[11]==1)
					$color = 'style="color:green;"';
				else if($data[11]==2)
					$color = 'style="color:blue;"';
				else if($data[11]==0)
					$color = 'style="color:red;"';
					
				$altTxt = "<td valign=top align=left>---</td>";
					//grad-alert-icon
				$mapTable .='<tr style="font-weight:bold;">';
				$mapTable .='<td valign="top" align="left">'.($c+$_POST[nr]).'</td>';
				
				if($data[12])
				$mapTable .='<td valign="top" align="left"><img src="unit_img/'.$data[12].'" width="50" height="40"/><br>'.$data[1].'</td>';
				else 
				$mapTable .='<td valign="top" align="left"><img src="images/popup_img.gif" width="50" height="40"/><br>'.$data[1].'</td>';
				
				
				if($data[4] == "Subscription Date Expired.Please Renew the Unit")
				{
					$mapTable .='<td '.$color.' valign="top" align="left" colspan=8>'.$data[4].'</td>';
				}
				elseif($data[4] == "a")
				{
					$mapTable .='<td valign="top" style="text-align:center">'.$data[15].'</td>';
					//$latlngloca = $data[7].','.$data[6];
					//$mapTable .='<td '.$color.' id="loca'.$i.'" valign="top" align="left"><script language="javascript">findLocat("'.$latlngloca.'","loca'.$i.'");<script></td>';
					$mapTable .= '<td '.$color.' id="loca'.$i.'" valign="top" align="left">'.getHomeGeoAddress($data[7],$data[6]).'</td>';
					if($data[13]!="")
					{
					$altTxt = "<td valign=top align=left>
				<img src=images/grad-alert-icon.png width=25 height=25 title=Alerts onmouseover=mopen('".$data[14]."') onmouseout=mclosetime() />".$data[13]."</td>";
					}
					else
					{
						$altTxt = "<td valign=top align=left> <img src=images/no-alert.png width=25 height=25 title='No Alerts' alt='No Alerts'  />".$data[13]."</td>";
					}
					
					$mapTable .='<td valign="top" align="left">'.$data[9].' '.date("h:i:s A",strtotime($data[10])).'</td>';
					$mapTable .='<td valign="top" align="left">Run Today = '.floor($data[16]).'<br> Odometer = '.floor($data[2]).'</td>';
					$mapTable .='<td valign="top" align="left">'.$data[3].'</td>';
					$mapTable .= $altTxt;
					$mapTable .='<td valign="top" align="left">'.$status.'</td>';
					$d1 = explode('-',$data[9]);
					$mapTable .="<td valign=top align=left><img src=images/google_maps_icon.png width=30 height=30 border=0 style='cursor:pointer' onclick=openPath(".$data[17].",'".$data[9]."',".$data[18].",".$data[5]."); title='Click to see it on Map' alt='Click to see it on Map' /></td>";
				}
				elseif($data[4] == "b")
				{
					$mapTable .='<td colspan="7" '.$color.' valign="top" align="left">Not Available</td>';
				}
				
				
				$mapTable .='</tr>';
				//exit;
				$c++;
			}
			echo $mapTable;
		}
		else
		{
			$meterArr1 = "";	
		}
		
		echo $meterArr1;

	}// If
	if($tot >= 6)
	{
	 ?>
     <tr>
        <td colspan="10"><?php paginate($tot,$n,$pg); ?></td>
      </tr>
     
     <?php } ?>
     </table>
</div>
</div>

<form name="formpagination" id="formpagination" action="#" method="post">
  <input type="hidden" name="pn" id="pn" value="<?php if(isset($_POST[pn])) echo $_POST[pn]; else echo '1'; ?>" />
  <input type="hidden" name="nr" id="nr" value="<?php echo $_POST[nr]?>" />
  <input type="hidden" name="pageSelect" value="" />
</form>
<form name="frmTripData" id="frmTripData" method="post" action="../tr/" target="_blank">
<input type="hidden" name="txtVehino" id="txtVehino" />
<input type="hidden" name="txtDate" id="txtDate" />
<input type="hidden" name="txtFromTime" id="txtFromTime" value="00:01" />
<input type="hidden" name="txtToTime" id="txtToTime" value="23:59" />
<input type="hidden" name="txtSessId" id="txtSessId" />
<input type="hidden" name="txtRunFlag" id="txtRunFlag" />
</form>

<form name="frmSubmit" id="frmSubmit" method="post">
    <input type="hidden" name="txtAlertId" id="txtAlertId" />
</form>